﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using Beeldbankmvc.Helpers;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace Beeldbankmvc.Models
{
    public class CollectionRepository: IDisposable
    {
        BeeldbankLinqDataContext db = new BeeldbankLinqDataContext();

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                // dispose managed resources
                db.Dispose();
            }
            // free native resources
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public IQueryable<BEELDBANK_COLLECTION> FindAll()
        {
            return db.BEELDBANK_COLLECTIONs;
        }

        public IQueryable<BEELDBANK_COLLECTION> FindAllSortedByName()
        {
            return FindAll().OrderBy(m => m.Name);
        }

        public IQueryable<ObjectCollection> FindCollections(int mediaObjectId)
        {
            var a = from b in db.BEELDBANK_MEDIAOBJECT_COLLECTIONs
                    where b.MediaObjectId == mediaObjectId
                    orderby b.BEELDBANK_COLLECTION.Name
                    select new ObjectCollection
            {
                MediaObjectId = b.MediaObjectId,
                CollectionId = b.BEELDBANK_COLLECTION.Id,
                CollectionName= b.BEELDBANK_COLLECTION.Name
            };

            return a;
        }

        public int FindCollectionByName(int mediaObjectId, string collectionName)
        {
            var a = from b in db.BEELDBANK_MEDIAOBJECT_COLLECTIONs
                    where b.MediaObjectId == mediaObjectId
                    &&
                    b.BEELDBANK_COLLECTION.Name == collectionName
                    orderby b.BEELDBANK_COLLECTION.Name
                    select new ObjectCollection
                    {
                        MediaObjectId = b.MediaObjectId,
                        CollectionId = b.BEELDBANK_COLLECTION.Id,
                        CollectionName = b.BEELDBANK_COLLECTION.Name
                    };

            return a.Count();
        }

        public CollectionModel FindOne(int id)
        {
            CollectionModel model = new CollectionModel();
            BEELDBANK_COLLECTION collection = db.BEELDBANK_COLLECTIONs.SingleOrDefault(m => m.Id == id);

            model.Id = collection.Id;
            model.Name = collection.Name;
            model.Description = collection.Description;
            model.Keywords = collection.Keywords.Replace("|"," ");
            model.AppApproved = collection.AppApproved;

            return model;
        }

        public CollectionModel FindOneByName(string name)
        {
            CollectionModel model = new CollectionModel();
            BEELDBANK_COLLECTION collection = db.BEELDBANK_COLLECTIONs.SingleOrDefault(m => m.Name == name);

            model.Id = collection.Id;
            model.Name = collection.Name;
            model.Description = collection.Description;
            model.Keywords = collection.Keywords.Replace("|", " ");
            model.AppApproved = collection.AppApproved;

            return model;
        }

        public void Add(CollectionModel model)
        {
            BEELDBANK_COLLECTION newCollection = new BEELDBANK_COLLECTION();

            newCollection.Name = model.Name;
            newCollection.Description = model.Description;
            newCollection.Keywords = model.Keywords.Replace(" ","|");
            newCollection.AppApproved = model.AppApproved;
            
            db.BEELDBANK_COLLECTIONs.InsertOnSubmit(newCollection);
        }

        public void SaveThumbnail(HttpRequestBase Request, CollectionModel model)
        {
            foreach (string inputTagName in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[inputTagName];
                if (file.ContentLength > 0)
                {
                    if (inputTagName.Equals("imageUpload"))
                    {
                        // Determine extension
                        string extension = file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
                        // Determine first part of the filename
                        string fileName = "";
                        fileName = ConfigurationManager.AppSettings["appData"];
                        // Check if directory exists
                        Tools.CheckDir(fileName);
                        // Creeer de nieuwe filenaam en forceer de juiste extensie
                        // Complete the filename for the full version
                        fileName += "\\" + model.Id.ToString();
                        if ((extension == "jpg") || (extension == "tif"))
                        {
                            // Complete the filename for the full version
                            fileName += "." + extension;
                            // Upload the image in the current format and correct extension
                            file.SaveAs(fileName);
                        }
                        else
                        {
                            // Set extension to JPG
                            extension = "jpg";
                            // Complete the filename for the full version
                            fileName += "." + extension;
                            // Create a temporary filename
                            string fileNameTmp = "";
                            fileNameTmp = ConfigurationManager.AppSettings["appData"] +"\\" + model.Id.ToString() + ".tmp";
                            // Upload the image in the current format and temporary filename
                            file.SaveAs(fileNameTmp);
                            // Create an image in memory from the source file
                            Bitmap bmp = (Bitmap)Image.FromFile(fileNameTmp);
                            // Save the image file from memory and convert it to a jpg file and save it in the destination directory
                            bmp.Save(fileName, ImageFormat.Jpeg);
                            bmp.Dispose();
                            // Remove the temporary image
                            File.Delete(fileNameTmp);
                        }

                        // Create a thumbnail in memory from the source file that was just recently created or moved
                        model.ThumbNail = ImageManipulation.ReadBitmap2ByteArray(ImageManipulation.CreateThumbnail(fileName, 250, 0));
                    }
                }
            }
        }

        public void Update(CollectionModel model)
        {
            BEELDBANK_COLLECTION collection = db.BEELDBANK_COLLECTIONs.SingleOrDefault(m => m.Id == model.Id);
            
            collection.Name = model.Name;
            collection.Description = model.Description;
            model.Keywords = " " + model.Keywords + " ";
            collection.Keywords = model.Keywords.Replace("  ", " ").Replace(",","").Replace(" ","|");
            collection.AppApproved = model.AppApproved;
        }

        public void Delete(CollectionModel model)
        {
            BEELDBANK_COLLECTION collection = db.BEELDBANK_COLLECTIONs.SingleOrDefault(m => m.Id == model.Id);

            // Determine first part of the filePath
            string fileName = ConfigurationManager.AppSettings["appData"] + "\\" + model.Id.ToString() + ".jpg";
            // Deleting the file
            File.Delete(fileName);

            db.BEELDBANK_COLLECTIONs.DeleteOnSubmit(collection);
        }

        public void Save()
        {
            db.SubmitChanges();
        }

        #region metroThemesList
        public IQueryable<JsonThemeResultsViewModel> metroThemesList(int typeId)
        {
            // select COUNT(*), BMC.CollectionId, BC.Name, BC.Description
            // from BEELDBANK_MEDIAOBJECT_COLLECTION BMC, BEELDBANK_COLLECTION BC
            // where BMC.CollectionId = BC.Id
            // and BC.AppApproved = 1
            // group by BMC.CollectionId, BC.Name, BC.Description
            // order by BC.Name

            var a = from bmc in db.BEELDBANK_MEDIAOBJECT_COLLECTIONs
                    join bc in db.BEELDBANK_COLLECTIONs on bmc.CollectionId equals bc.Id
                    join bm in db.BEELDBANK_MEDIAOBJECTs on bmc.MediaObjectId equals bm.Id
                    where (bc.AppApproved == true) && (bm.TypeId == typeId)
                    group bmc by new
                    {
                        bmc.CollectionId,
                        bmc.BEELDBANK_COLLECTION.Name,
                        bmc.BEELDBANK_COLLECTION.Description
                    } into c
                    orderby c.Key.Name
                    select new JsonThemeResultsViewModel
                    {
                        CollectionId = c.Key.CollectionId,
                        CollectionName = c.Key.Name,
                        CollectionDescription = c.Key.Description,
                        CollectionImage = ConfigurationManager.AppSettings["MediaObjectLibraryAppData"] + "/" + c.Key.CollectionId.ToString() + ".jpg",
                        CollectionCount = c.Count()
                    };
            return a;
        }
        #endregion
    }

    public class ObjectCollection
    {
        public int MediaObjectId { get; set; }
        public int CollectionId { get; set; }
        public string CollectionName { get; set; }
    }
}